<?php

namespace app\admin\behavior;
use app\admin\model\Admin;
use fast\Pinyin;
use fast\Random;
use think\Db;
use think\exception\ValidateException;


/**
 * 生成管理员账号，并把账号加入对应权限组
 * 企业账号权限组：3，经销商权限组为4 ，平台管理员组为2，超级管理员组为1
 */
class AdminAuth
{

    protected $auth = [
        1 => 3, //企业管理员
        2 => 4  //经销商
    ];
    public function adminAuth(&$params)
    {
        self::createAdmin($params);
    }

    /**
     * 删除数据
     * 删除权限和分组数据
     */
    public function adminDel(&$params) {
        $type = intval($params['type']); //角色类型
        $type_id = $params['type_id']; //角色id

        if (!$type_id || !in_array($type, [1, 2])) {
            throw new ValidateException('参数错误');
        }

        $adminModel = new  Admin();
        $res = $adminModel->destroy(['type' => $type, 'type_id'=> $type_id]);
        if ($res === false) {
            throw new ValidateException('删除失败');
        }

        return true;
    }

    /**
     * 生成管理员账号
     * @param Object $company
     * name:企业名称
     * id: 企业id
     * type: 账号类型
     */
    private function createAdmin($data) {
        $pinyin = Pinyin::get($data['name']);
        $admin['username'] = substr($pinyin, 0, 6).''.$data['id'];
        $admin['nickname'] = $data['name'];
        $admin['email'] = isset($data['email'])? $data['email'] : '';
        $admin['salt'] = Random::alnum();
        $admin['password'] = md5(md5(123456) . $admin['salt']);
        $admin['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
        $admin['type'] = $data['type']; //角色。
        $admin['type_id'] = $data['id']; //角色对应id
        $adminModel = new Admin();
        $res = $adminModel->validate('Admin.add')->data($admin)->isUpdate(false)->save();

        if ($res === false) {
            throw new ValidateException('企业生成管理员失败');
        }

        self::joinAuth($data['type'], $adminModel->id);
        return true;
    }

    /**
     * 加入权限组
     * type为账号类别
     * id为账号id
     */
    private function joinAuth($type, $id) {
        if (!$id || !in_array($type, [1, 2])) {
            throw new ValidateException('参数错误');
        }
        $type = intval($type);
        $authId = $this->auth[$type];
        //把用户加入权限组
        Db::name('auth_group_access')->insert([
            'uid' =>$id,
            'group_id' => $authId //定死的
        ]);

        return true;
    }


}
